<template>
	<view>
		<up-navbar title="添加教育经历" @leftClick="leftClick" safeAreaInsetTop placeholder>
		</up-navbar>
		<up-form  labelWidth="80" labelPosition="left" :model="model1" :rules="rules"
			ref="form1">
			<up-divider></up-divider>
			<up-form-item prop="educationExperience.school">
				<template #label>
					<up-row>
						<up-col span="4">
							<up-text text="学校" align="center" size="20px"
								@blur="validateField('educationExperience.school')"></up-text>
						</up-col>
						<up-col offset="1" span="7">
							<up-input placeholder="请输入" font-size="20px" v-model="model1.educationExperience.school"
								border="none"></up-input>
							<up-text v-if="errors.school" color="red" :bold="true" text="请输入学校名称"></up-text>
						</up-col>
					</up-row>
				</template>
			</up-form-item>
			<up-divider></up-divider>
			<up-form-item prop="educationExperience.education" @click="openEduSelect">
				<template #label>
					<up-row>
						<up-col span="4">
							<up-text text="学历" align="center" size="20px"
								@blur="validateField('educationExperience.education')"></up-text>
						</up-col>
						<up-col offset="0.7" span="7">
							<up-input placeholder="请选择" font-size="20px" v-model="model1.educationExperience.education"
								border="none" :disabled="true" disabled-color="#ffffff"></up-input>
							<up-text v-if="errors.education" color="red" :bold="true" text="请选择学历"></up-text>
						</up-col>
						<up-col span="1" offset="2.5">
							<up-icon name="arrow-right" style=""></up-icon>
						</up-col>
					</up-row>
				</template>
			</up-form-item>
			<up-picker :show="eduShow" ref="uPickerRef" :closeOnClickOverlay="true" :defaultIndex="defaultIndex"
				:columns="eduColumns" @cancel="eduShow = false" @close="eduShow = false" @confirm="educationConfirm"
				@change="changeHandler"></up-picker>
			<up-divider></up-divider>
			<div v-if="showMajor()">
				<up-form-item prop="educationExperience.major">
					<template #label>
						<up-row>
							<up-col span="4">
								<up-text text="专业" align="center" size="20px"
									@blur="validateField('educationExperience.major')"></up-text>
							</up-col>
							<up-col offset="1" span="7">
								<up-input placeholder="请输入" font-size="20px" v-model="model1.educationExperience.major"
									border="none"></up-input>
								<up-text v-if="errors.major" color="red" :bold="true" text="请输入专业"></up-text>
							</up-col>
						</up-row>
					</template>
				</up-form-item>
				<up-divider></up-divider>
			</div>
			<up-row>
				<up-col span="2.5">
					<up-text text="时间段" align="center" size="20px"></up-text>
				</up-col>
				<up-col span="3" offset="1">
					<up-form-item prop="educationExperience.enrollmentDate" borderBottom ref="item1">
						<up-text :text="model1.educationExperience.enrollmentDate" size="20px" :color="startColor"
							@click="startShow=true"></up-text>
					</up-form-item>
					<up-text v-if="errors.enrollmentDate" color="red" :bold="true" text="请选择时间"></up-text>
				</up-col>
				<up-col span="1">
					——
				</up-col>
				<up-col span="3" offset="0.5">
					<up-form-item prop="educationExperience.graduationDate" borderBottom ref="item1">
						<up-text :text="model1.educationExperience.graduationDate" size="20px" :color="endColor"
							@click="endShow=true"></up-text>
					</up-form-item>
					<up-text v-if="errors.graduationDate" color="red" :bold="true" text="请选择时间"></up-text>
				</up-col>
			</up-row>
			<up-divider></up-divider>
			<div>
				<up-form-item prop="educationExperience.majorRank">
					<template #label>
						<up-row>
							<up-col span="4">
								<up-text text="专业排名" align="center" size="20px"
									@blur="validateField('educationExperience.majorRank')"></up-text>
							</up-col>
							<up-col offset="1" span="7">
								<up-input placeholder="请输入" font-size="20px"
									v-model="model1.educationExperience.majorRank" border="none"></up-input>
								<up-text v-if="errors.majorRank" color="red" :bold="true" text="请输入专业排名"></up-text>
							</up-col>
						</up-row>
					</template>
				</up-form-item>
			</div>
			<up-form-item prop="educationExperience.schoolExperience" borderBottom ref="item1">
				<up-cell-group>
					<up-cell :border="false">
						<template #title>
							<up-text text="在校经历" size="20px" style="margin-left: -5px;"></up-text>
						</template>
					</up-cell>
					<up-cell @click="editEduContent" :border="false">
						<template #title>
							<up-text :text="model1.educationExperience.schoolExperience" lines="2" size="20px"
								:color="eduContentColor"></up-text>
							<up-text v-if="errors.schoolExperience" color="red" :bold="true" text="请输入校园经历"></up-text>
						</template>
						<template #right-icon>
							<up-icon name="arrow-right" style="margin-right: 20px;"></up-icon>
						</template>
					</up-cell>
				</up-cell-group>
			</up-form-item>
			<up-datetime-picker :show="startShow" v-model="startValue" mode="year-month" @confirm="startTimeConfirm"
				@cancel="startShow=false" @close="startShow=false" :closeOnClickOverlay="true"></up-datetime-picker>
			<up-datetime-picker :show="endShow" v-model="endVaule" mode="year-month" @confirm="endTimeConfirm"
				@cancel="endShow=false" @close="endShow=false" :closeOnClickOverlay="true"></up-datetime-picker>
		</up-form>
		<view class="save">
			<up-button type="error" v-if="model1.educationExperience.experienceId != ''"
				style="margin-right: 10px;width: 200px;" size="large" text="删除" @click="delShow = true"></up-button>
			<up-button type="primary" size="large" text="保存" @click="submitForm()"></up-button>
		</view>
		<up-modal :content="content" :show="show" showCancelButton closeOnClickOverlay @confirm="submitForm()"
			@cancel="cancel" @close="show = false" contentTextAlign="center"></up-modal>
		<up-modal :content="delContent" :show="delShow" showCancelButton closeOnClickOverlay @confirm="delForm()"
			@cancel="cancel" @close="delShow = false" contentTextAlign="center"></up-modal>
	</view>
</template>

<script>
	export default {
		onShow() {
			//获取工作内容传回的对象
			uni.getStorage({
				key: 'eduContent',
				success: (res) => {
					console.log('获取的数据：', res.data);
					this.eduContent = res.data;
				},
				fail: (err) => {
					// console.error('获取数据失败：', err);
					this.eduContent = err.data;
				},
			});
			console.log('jobContent:', this.eduContent); // 输出实际内容
			if (this.eduContent !== null && this.eduContent !== undefined) {
				if (uni.getStorageSync('eduContent') !== '') {
					const data = uni.getStorageSync('eduContent');
					if (data !== 'cancel') {
						this.model1.educationExperience.schoolExperience = data;
						this.eduContentColor = 'black';
						uni.removeStorageSync('eduContent');
					} else {
						uni.removeStorageSync('eduContent');
					}
				} else {
					this.model1.educationExperience.schoolExperience = '请输入';
					this.eduContentColor = '#c4c9cf'
				}
			}
		},
		onLoad(options) {

			if (options.value != null) {
				this.model1.educationExperience = JSON.parse(options.value);
				this.submitStartTime = this.convertToTimestamp(this.model1.educationExperience.enrollmentDate);
				this.submitEndTime = this.convertToTimestamp(this.model1.educationExperience.graduationDate);
				this.startColor = 'black';
				this.endColor = 'black;'
				this.eduContentColor = 'black'
			}
		},
		data() {
			return {
				model1: {
					educationExperience: {
						id: '',
						resumeId: 1,
						school: '',
						education: '',
						major: '',
						enrollmentDate: '入学时间',
						graduationDate: '毕业时间',
						majorRank: '',
						schoolExperience: '请输入'
					}
				},
				errors: {
					school: '',
					education: '',
					major: '',
					enrollmentDate: '',
					graduationDate: '',
					majorRank: '',
					schoolExperience: ''
				},
				//入学时间
				startShow: false,
				startValue: Number(new Date()),
				startColor: '#c4c9cf',
				//入学时间展示
				submitStartTime: '',
				//毕业时间
				endShow: false,
				endVaule: Number(new Date()),
				endColor: '#c4c9cf',
				//毕业时间展示
				submitEndTime: '',
				//学历
				eduShow: false,
				//学历默认选项
				defaultIndex: [1, 0],
				eduColumns: [
					['高中', '大专', '本科', '硕士', '博士'],
					['全日制', '非全日制']
				],
				columnData: [
					[''],
					['全日制', '非全日制'],
				],
				//在校经历
				eduContentColor: '#c4c9cf',
				eduContent: '',
				//左上角返回
				content: '是否要保存再返回',
				show: false,
				//删除
				delContent: '确定要删除该经历？',
				delShow: false,
			}
		},
		methods: {
			//判断是否为空
			validateField(field) {
				switch (field) {
					case 'school':
						this.errors.school = this.model1.educationExperience.school ? '' : '请输入学校名称';
						break;
					case 'education':
						this.errors.education = this.model1.educationExperience.education ? '' : '请选择学历';
						break;
					case 'major':
						this.errors.major = this.model1.educationExperience.major === '' ? '请输入专业' : '';
						break;
					case 'enrollmentDate':
						this.errors.enrollmentDate = this.model1.educationExperience.enrollmentDate === '入学时间' ?
							'请选择入学时间' : '';
						break;
					case 'graduationDate':
						this.errors.graduationDate = this.model1.educationExperience.graduationDate === '毕业时间' ?
							'请输入毕业时间' : '';
						break;
					case 'majorRank':
						this.errors.majorRank = this.model1.educationExperience.majorRank === '' ? '请输入专业排名' : '';
						break;
					case 'schoolExperience':
						this.errors.schoolExperience = this.model1.educationExperience.schoolExperience === '请输入' ?
							'请输入学校经历' : '';
						break;
				}
			},
			//点击左上角返回
			leftClick() {
				this.show = true;
			},
			//展示专业
			showMajor() {
				if (this.model1.educationExperience.education === '高中' || this.model1.educationExperience.education ===
					'') {
					return false;
				} else {
					return true;
				}
			},
			//设置默认时间
			setYears(date, years) {
				const newDate = new Date(date);
				newDate.setFullYear(newDate.getFullYear() + years);
				return newDate;
			},
			//起始时间确认
			startTimeConfirm(startDate) {
				console.log('startDate.value:', startDate.value); // 调试输出  

				const date = new Date(startDate.value);
				if (isNaN(date.getTime())) {
					console.error('Invalid date:', startDate.value);
					return; // 处理无效日期的逻辑  
				}
				this.submitStartTime = startDate.value;
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const formattedDate = `${year}-${month}`;

				this.model1.educationExperience.enrollmentDate = formattedDate;
				this.startColor = 'black';
				//设置毕业时间为当前时间+4年
				let graduateTime = `${year+4}-${month}`;
				this.model1.educationExperience.graduationDate = graduateTime;
				this.submitEndTime = this.convertToTimestamp(graduateTime)
				this.endColor = 'black';
				this.startShow = false;
			},
			//毕业时间确认
			endTimeConfirm(endDate) {
				// 检查 endDate.value 是否有效
				if (!endDate.value || isNaN(endDate.value)) {
					console.error('无效的日期值:', endDate.value);
					return; // 终止执行  
				}
				this.submitEndTime = endDate.value;
				// 将时间戳转换为 Date 对象
				const date = new Date(endDate.value);
				// 获取年份和月份  
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，所以需要加 1，并且补零  
				// 格式化为 "年 - 月" 的形式  
				const formattedDate = `${year}- ${month}`;
				//存值
				this.model1.educationExperience.graduationDate = formattedDate;
				//调色
				this.endColor = 'black';
				//关闭选择器
				this.endShow = false;
			},
			//将年-月转换为时间戳
			convertToTimestamp(yearMonth) {
				// 将字符串转换为日期对象  
				const [year, month] = yearMonth.split('-');
				// 创建一个新的 Date 对象，设置为该月的第一天  
				const date = new Date(year, month - 1); // month - 1 因为月份是从 0 开始的  
				// 获取时间戳（以毫秒为单位）  
				return date.getTime(); // 返回时间戳  
			},
			//将时间戳转换为dateTime形式
			changeToDateTime(timestamp) {
				const date = new Date(timestamp);

				// 获取年、月、日、时、分、秒  
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以加1  
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				const seconds = String(date.getSeconds()).padStart(2, '0');

				// 格式化为 ISO 8601 格式  
				const dateTimeString = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.000Z`;
				return dateTimeString;
			},
			//打开学历选择器
			openEduSelect() {
				this.eduShow = true;
				this.$refs.uPickerRef.setColumnValues(0, this.eduColumns[0])
			},

			//学历确认
			educationConfirm(value) {
				this.eduShow = false;
				if (value.value[0] === '高中') {
					this.model1.educationExperience.education = value.value[0];
				} else {
					this.model1.educationExperience.education = `${value.value[0]}-${value.value[1]}`
				}
			},
			//学历左右联动
			changeHandler(e) {
				const {
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index
				} = e
				console.log(value)
				if (columnIndex === 0) { // 如果第一列发生变化  
					// 根据选择更新第二列  
					if (value[0] === '高中') {
						this.$refs.uPickerRef.setColumnValues(1, this.columnData[0]);
					} else {
						this.$refs.uPickerRef.setColumnValues(1, this.columnData[1]);
					}
				}
			},
			//编辑在校经历
			editEduContent() {
				let str = encodeURIComponent(JSON.stringify(this.model1.educationExperience))
				uni.navigateTo({
					url: "/pages/personal/eduContentView?eduContent=" + str
				})
			},
			//删除该经历
			delForm() {
				//调用数据库删除
				this.$api.delEduExp({
					id: this.model1.educationExperience.id
				}).then((res) => {
					if (res.data === 'ok') {
						uni.showToast({
							title: '删除成功',
							icon: 'success',
							complete() {
								uni.navigateTo({
									url: "/pages/personal/onlineResumeView"
								})
							}
						})
					} else {
						uni.showToast({
							title: '删除失败',
							icon: 'fail',
						})
					}
				})
				//返回
				uni.navigateTo({
					url: "/pages/personal/onlineResumeView"
				})
			},
			//左上角弹出框取消
			cancel() {
				uni.navigateTo({
					url: "/pages/personal/onlineResumeView"
				})
			},
			//返回弹出框保存+下方保存
			submitForm() {
				this.validateField('school');
				this.validateField('education');
				this.validateField('major');
				this.validateField('enrollmentDate');
				this.validateField('graduationDate');
				// this.validateField('majorRank');
				this.validateField('schoolExperience');
				// 检查是否有错误
				let hasError = false;
				for (let key in this.errors) {
					if (this.errors[key]) {
						hasError = true;
						break;
					}
				}
				// 检查时间是否正确
				if (this.model1.educationExperience.enrollmentDate > this.model1.educationExperience.graduationDate) {
					uni.showToast({
						title: '入学时间必须小于毕业时间',
						icon: 'none'
					});
					return;
				}
				// 检查入职时间是否大于当前时间
				if (new Date(this.model1.educationExperience.enrollmentDate) > new Date()) {
					uni.showToast({
						title: '入学时间不能大于当前时间',
						icon: 'none'
					});
					return;
				}
				if (hasError) {
					this.show = false;
					return;
				}
				console.log(this.submitEndTime)
				// 保存数据
				if(this.model1.educationExperience.id !== ''){
					this.$api.updateEduExp({
						id:this.model1.educationExperience.id,
						resumeId:this.model1.educationExperience.resumeId,
						school:this.model1.educationExperience.school,
						education:this.model1.educationExperience.education,
						enrollmentDate:this.changeToDateTime(this.submitStartTime),
						graduationDate:this.changeToDateTime(this.submitEndTime),
						major:this.model1.educationExperience.major,
						majorRank:this.model1.educationExperience.majorRank,
						schoolExperience:this.model1.educationExperience.schoolExperience,
					}).then((res) => {
						uni.showToast({
							title: `${res.code === 200 ? '修改成功' : '修改失败'}`,
							icon: 'none'
						});
						uni.navigateTo({
							url: "/pages/personal/onlineResumeView"
						});
					})
				}else{
					this.$api.addUserEduExp({
						resumeId:this.model1.educationExperience.resumeId,
						school:this.model1.educationExperience.school,
						education:this.model1.educationExperience.education,
						enrollmentDate:this.changeToDateTime(this.submitStartTime),
						graduationDate:this.changeToDateTime(this.submitEndTime),
						major:this.model1.educationExperience.major,
						majorRank:this.model1.educationExperience.majorRank,
						schoolExperience:this.model1.educationExperience.schoolExperience,
					}).then((res) => {
						uni.showToast({
							title: `${res.code === 200 ? '保存成功' : '保存失败'}`,
							icon: 'none'
						});
						uni.navigateTo({
							url: "/pages/personal/onlineResumeView"
						});
					})
				}
			},
		}
	}
</script>

<style>
	.save {
		position: fixed;
		bottom: 0;
		width: 95%;
		background-color: #fff;
		padding: 10px;
		box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
		display: flex;
	}

	.custom-error {
		color: blue;
		/* 修改错误提示颜色 */
		font-weight: bold;
		/* 加粗 */
		margin-top: 5px;
		/* 提示和输入框之间的间距 */
	}
</style>